<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\Vercode;
use app\index\model\User;
use think\Loader;
require_once("../vendor/qqConnect/API/qqConnectAPI.php");
class Login extends Common
{
    public function index()
    {
        // 从数据库中随机获取 一个问题，把答案存储在session;
        
        $question = (new Vercode)->getRandOne();
        // 分配变量
        $this->assign('question',$question);
        $this->assign('title',"登录");
        // 引一个页面
        return $this->fetch();
    }

    public function checklogin()
    {
        // // 1 接收所有注册的数据 
        $data = input('post.');

        //  // 2 验证数据 

        $validate = Loader::validate('Login');

        if(!$validate->check($data)){
            $this->error($validate->getError());
        }else{
            $this->success("登录成功");
        }
    }

    public function loginout()
    {
        session('uid',null);
        // header("Location:".url('index/login/index'));
        // exit;
        $this->success("退出成功",url('index/login/index'));
    }

    public function qq(){

        
        $qc = new \QC();
        $qc->qq_login();
        exit();
    }

    public function qqreturn()
    {
        $qc = new \QC();

        $qc->qq_callback();

        $openid = $qc->get_openid();

        $user = User::get(['openid'=>$openid]);

        if($user){
            session('nickname',$user->nickname);
            session('uid',$user->uid);
            session('face',$user->face);
            $this->success("qq登录成功",url('index/user/index'));
        }else{

            $data = [];

            // $qc = new QC();
            $arr = $qc->get_user_info();

            $data['nickname'] = $arr['nickname'];
            $data['face'] = $this->getQQFace($arr['figureurl_2']);
            $data['sex'] = $arr['gender'];
            $data['city'] = $arr['city'];
            $data['openid'] = $openid;
            $data['ctime'] =time();


            $userModel = new User();

            $user = $userModel->data($data)->save();

            if($user){
                session('nickname',$userModel['nickname']);
                session('uid',$userModel->uid);
                session('face',$userModel->face);
                $this->success("qq-reg登录成功",url('index/user/index'));
            }
        }
    }

    public function wxlogin(){

        $returnUrl = "http://1o533n8683.imwork.net".url('index/login/wxreturn');

        $returnUrl = urlencode($returnUrl);

        $url  = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".config('site.APPID')."&redirect_uri=".$returnUrl."&response_type=code&scope=snsapi_base&state=123#wechat_redirect";

        // $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".config('site.APPID')."&redirect_uri=".$returnUrl."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

        header("Location:".$url);exit;

        // echo ($url);

    }

    public function wxreturn()
    {

        $code = input('code');

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".config('site.APPID')."&secret=".config('site.APPSECRET')."&code=".$code."&grant_type=authorization_code";


        $data = file_get_contents($url);

        $data = json_decode($data,true);

        $openid = $data['openid'];

        $user = User::get(['openid'=>$openid]);

        if($user){
            session('nickname',$user->nickname);
            session('uid',$user->uid);
            session('face',$user->face);
            header('Location:'.url(session('wxurl')));
            // $this->success("qq登录成功",url('index/user/index'));
        }else{

            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$openid."&lang=zh_CN";

            $data1 = file_get_contents($url);

            $data1 = json_decode($data1,true);

            $data = [];

            $data['nickname'] = $data1['nickname'];
            $data['face'] = $this->getQQFace($data1['headimgurl']);
            $data['sex'] = $data1['sex'] ? '男':'女';
            $data['city'] = $data1['city'];
            $data['openid'] = $openid;
            $data['ctime'] =time();

            $userModel = new User();

            $user = $userModel->data($data)->save();

            if($user){
                session('nickname',$userModel['nickname']);
                session('uid',$userModel->uid);
                session('face',$userModel->face);
                header('Location:'.url(session('wxurl')));
            }
        }



        // var_dump($data);

    }

    public function getQQFace($url)
    {

        // $url = "http://qzapp.qlogo.cn/qzapp/101483441/6033A922958055B00D519FF183CEDB70/100";


        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($curl, CURLOPT_HEADER, false);

        $data= curl_exec($curl);
        // $data = file_get_contents($url);

        $name = "uploads/".date("Ymd")."/".uniqid().".png";


        is_dir(dirname($name)) || mkdir(dirname($name));


        file_put_contents($name,$data);

        return $name;

    }
}
